//
//  PersistenceViewController.m
//  Persistence
//
//  Created by jeff on 4/23/09.
//  Copyright Jeff LaMarche 2009. All rights reserved.
//

#import "PersistenceViewController.h"

@implementation PersistenceViewController
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;

- (NSString *)dataFilePath {
    //获取document目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                         NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@", paths);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"%@", documentsDirectory);
    
    //在document目录下，新建文件data.plist
    return [documentsDirectory stringByAppendingPathComponent:kFilename];
}

- (void)applicationWillTerminate:(NSNotification *)notification {
    //将数据写入到plist    
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObject:field1.text];
    [array addObject:field2.text];
    [array addObject:field3.text];
    [array addObject:field4.text];
    [array writeToFile:[self dataFilePath] atomically:YES];
    [array release];
}

- (NSString *)documentsDir {
    //获取document目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                         NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@", paths);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"%@", documentsDirectory);
    return documentsDirectory;
}



#pragma mark -
- (void)viewDidLoad {
    
    NSString *filePath = [self dataFilePath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        //从plist中读取数据
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        field1.text = [array objectAtIndex:0];
        field2.text = [array objectAtIndex:1];
        field3.text = [array objectAtIndex:2];
        field4.text = [array objectAtIndex:3];
        [array release];
    }
    
    //注册UIApplicationWillTerminateNotification事件
    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillTerminate:)
                                                 name:UIApplicationWillTerminateNotification 
                                               object:app];
    [super viewDidLoad];
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
    self.field1 = nil;
    self.field2 = nil;
    self.field3 = nil;
    self.field4 = nil;
    [super viewDidUnload];
}
- (void)dealloc {
    [field1 release];
    [field2 release];
    [field3 release];
    [field4 release];
    [super dealloc];
}

#pragma mark - plist and data
//在iPhone  OS 系统上保存属性列表文件时，采用二进制格式进行存储是很重要的
//二进制格式比其它基于文本的格式紧凑得多，这种紧凑不仅使属性列表在用户设备上占用的空间最小，还可以减少读写属性列表的时间。
- (IBAction)plist2Data {
    //file path
    NSString * filepath = [[self documentsDir] stringByAppendingPathComponent:@"dic.plist"];
    
    //新建一个字典
    NSString * err;//不需要初始化。如果有错误发生，会被复制。
    NSDictionary *props = [NSDictionary dictionaryWithObjectsAndKeys:@"Lucy", @"name", 
                           @"Beijing", @"city",
                           @"supervior", @"position", 
                           @"Qitiandasheng", @"company", 
                           nil];
    
    //把字典转换为二进制，并写入文件
    //+ (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format errorDescription:(NSString **)errorString	
    //plist must be a kind of NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary object.
    NSData * data = [NSPropertyListSerialization dataFromPropertyList:props
                                                               format:NSPropertyListXMLFormat_v1_0 
                                                     errorDescription:&err];
    if(!err){
        [data writeToFile:filepath atomically:YES];//写入文件
    }else{
        NSLog(@"error with:%@", err);
    }
}

- (IBAction)data2Plist {
    //先读取到data
    NSString * filepath = [[self documentsDir] stringByAppendingPathComponent:@"dic.plist"];
    NSData* data = [NSData dataWithContentsOfFile:filepath];
    
    //再用data转换为plist
    NSString *error;
    NSPropertyListFormat format;
    NSDictionary* retPlist = [NSPropertyListSerialization propertyListFromData:data  
                                                              mutabilityOption:NSPropertyListImmutable  
                                                                        format:&format 
                                                              errorDescription:&error];
    if (!retPlist){
        NSLog(@"Plist not returned, error: %@", error);
    }
    NSLog(@"%@", retPlist);
}
@end
